import { useStore } from 'vuex'
import { computed } from 'vue'
// 购物车相关逻辑
export const useCommonCartEffect = (shopId) => {
  const store = useStore()
  const cartList = store.state.cartList
  const changeCartItemInfo = (shopId, productId, productInfo, changeNum) => {
    store.commit('changeCartItemInfo', {
      shopId, productId, productInfo, changeNum
    })
  }

  // 计算产品列表
  const productList = computed(() => {
    const productList = cartList[shopId]?.productList || []
    return productList
  })

  // TODO: 难点记录 因为可能刚开始取不到名字，后面又有名字，所以要用computed
  const shopName = computed(() => {
    const shopName = cartList[shopId]?.shopName || ''
    return shopName
  })

  // 计算价格，总数，是否全选
  const calculatioins = computed(() => {
    const productList = cartList[shopId]?.productList
    const result = { total: 0, price: 0, allChecked: true }
    if (productList) {
      for (const i in productList) {
        const product = productList[i]
        result.total += product.count
        if (product.check) {
          result.price += (product.count * product.price)
        }
        if (product.count > 0 && !product.check) {
          result.allChecked = false
        }
      }
      result.price = result.price.toFixed(2)
    }
    return result
  })

  return { changeCartItemInfo, cartList, productList, shopName, calculatioins }
}
